<script lang="ts">
	import Divider from '$components/basic/divider/divider.svelte';
	import Select, { Option } from '@smui/select';
	import Icon from '@smui/select/icon';
	import IconButton from '@smui/icon-button';
	import Card from './_com/card.svelte';
	import Button from '@smui/button';
	import { alova } from '$utils/request';
	import { onMount } from 'svelte';
	import Textfield from '@smui/textfield';
	import HelperText from '@smui/textfield/helper-text';
	import { useCartStore, useUserstore } from '@/store';
	import { usePreOrderStore } from '@/store/modules/pre';
	import Product from '$components/business/product/product.svelte';
	import { get } from 'svelte/store';
	import { createDialog } from '$components/basic/dialog/dialog';
	import { goto } from '$utils/intercept';
	import { showLoading } from '$components/basic/message';
	import { handleReq } from '@/hooks/handleReq';

	let content = '';

	type ApiRes = { code: number; data: any; message: string };
	type OptionsType = { label: string; value: string }[];

	let loading = true;
	let shipWay = '';
	let shipWayList: OptionsType = [];
	/** @description 获取配送方式 */
	const loadShipWay = async () => (await alova.Get('/order/transport')) as ApiRes;

	let active = 0;
	let address: CommonInfo.Address | null = null;
	let addressList: IObject[] = [];
	/** @description 获取地址信息 */
	const loadAddressList = async () => (await alova.Post('/member-address/list')) as ApiRes;

	let orderList: Partial<Product.Detail>[] = [];

	const initPreOrderToPage = () => {
		const { cartList } = useCartStore();
		const { preOrderList } = usePreOrderStore();
		const ids = get(preOrderList).map((i) => Number(i));
		orderList = get(cartList).filter((i) => ids.includes(Number(i.id)));
	};

	const getAddresAndShipWay = async () => {
		const result = await Promise.all([loadShipWay(), loadAddressList()]);
		const [{ data: ss }, { data: dd }] = result;
		return (
			ss &&
				(shipWayList = Object.keys(ss).map((i) => ({ label: ss[i], value: i }))) &&
				(shipWay = shipWayList[0].value),
			dd &&
				(addressList = Object.values(dd as CommonInfo.Address[]).map((ad) => {
					return {
						label:
							ad.fName +
							ad.lName +
							'  ' +
							ad.email +
							'\n' +
							ad.aDetail +
							',' +
							ad.aCity +
							',' +
							ad.aProvince +
							',' +
							ad.aCountry,
						value: ad.id
					};
				})),
			(loading = false)
		);
	};

	async function initPage() {
		initPreOrderToPage();
		getAddresAndShipWay();
	}

	onMount(initPage);

	$: amount = orderList.reduce(
		(pre, cur) =>
			pre + Number(cur.price) * Number(cur.num) * Number(cur.discount ? cur.discount : 1),
		0
	);

	const submit = async () => {
		const cartStore = useCartStore();
		// TODO: 提交订单
		const isLogin = get(useUserstore().token);
		const toLogin = () => goto('/login');
		if (!isLogin) return createDialog('Warning', 'Please login first', toLogin);

		const msg = showLoading();

		const params = {
			shipway: shipWay,
			content: content,
			addressId: addressList[active].value,
			goods_info: JSON.stringify(orderList.map((i) => ({ id: i.id, number: i.num })))
		};
		const { error, result } = await handleReq('/order/create', { params, msg });

		if (!error) {
			msg.close();
			orderList.map((i) => cartStore.removeCartItem(Number(i.id)));
			goto('/order/list');
		}
		console.log(get(result));
	};
</script>

<div class="w-full flex-cc">
	<div class="w-1320px max-w-100% min-w-350px flex flex-col py-20px gap-15px">
		<div
			class="w-full bg-yellow-1 shadow-md py-10px font-size-18px color-gray-5 px-20px flex flex-row justify-between items-center"
		>
			<span
				>Your order includes pre-sale item, so you can't pay. We will review and split the order
				within 48 hours.</span
			>
			<IconButton class="material-icons">close</IconButton>
		</div>
		<Card title="Order Detail" color="var(--mdc-theme-primary)" num={1}>
			<li
				class="font-bold grid grid-order-table h-32px line-height-32px font-size-16px color-gray-5 bg-white"
			>
				<span class="px-4">ID</span>
				<span class="px-4">Code No.</span>
				<span class="px-4">Item Name</span>
				<span class="px-4">Quantity</span>
				<span class="px-4">UnitPrice</span>
				<span class="px-4">Amount</span>
			</li>
			<Divider style="--mdc-theme-primary: #f3f4f6 " />
			{#each orderList as item, index (item.id)}
				<li
					class="font-bold grid grid-order-table h-32px line-height-32px font-size-16px color-gray-5 bg-white"
				>
					<span class="px-4">{index + 1}</span>
					<span class="px-4">{item.code}</span>
					<span class="px-4 whitespace-pre-wrap">{item.title}</span>
					<span class="px-4">{item.num}</span>
					<span class="px-4">$ {item.price}</span>
					<span class="px-4"
						>$ {(
							Number(item.num) *
							Number(item.price) *
							Number(item.discount ? item.discount : 1)
						).toFixed(2)}</span
					>
				</li>
			{/each}
		</Card>

		<Card title="Shipping Address" color="#fbbf24" num={2} bind:loading>
			<div class="w-full flex flex-col gap-15px px-2 pt-2 pb-4">
				<Select class="clear-select-underline w-full" variant="outlined" bind:value={shipWay}>
					<Icon class="material-icons" slot="leadingIcon">local_shipping</Icon>
					{#each shipWayList as way}
						<Option value={way.value}>{way.label}</Option>
					{/each}
				</Select>
				<div class="w-full font-size-16px color-gray-5 grid grid-cols-3 gap-20px">
					{#each addressList as item, index}
						<button
							class="reset-button cursor-pointer bg-transparent border-gray-2 border-solid border shadow-md rounded-md shadow-blue-7 relative flex items-center justify-start pl-20px h-64px animate-both animate-fade-in-up"
							style={`animation-delay: ${(index + 1) * 250}ms !important; ${active === index ? 'border-color: var(--mdc-theme-primary); color: var(--mdc-theme-primary);' : 'box-shadow: none !important;'}`}
							on:click={() => (active = index)}
						>
							<p class="text-left indent-0 m-0 whitespace-pre-wrap bg-transparent">
								{item.label}
							</p>
							<div
								class="absolute flex-cc w-30px h-30px bottom-10px right-10px font-size-24px"
								style={active === index ? 'display: block' : 'display: none'}
							>
								<span class="material-symbols-outlined"> check </span>
							</div>
						</button>
					{/each}
					<div
						class="flex-cc border border-solid h-64px bg-blue-1 button-box"
						style={`border-color: var(--mdc-theme-primary); color: var(--mdc-theme-primary);`}
					>
						<span class="material-symbols-outlined font-size-30px font-bold"> add </span>
					</div>
				</div>
			</div>
		</Card>
		<Card title="Order Comments" color="#4ade80" num={3}>
			<div
				class="flex justify-start items-center gap-5px ml-20px py-8px font-size-16px color-gray-5"
			>
				<span class="material-symbols-outlined"> chat </span>
				<span>if you have custom requirements for your order, please fill in here</span>
			</div>
			<div class="px-15px py-2">
				<Textfield
					style="width: 100%;"
					helperLine$style="width: 100%;"
					textarea
					bind:value={content}
					label="your comments"
				>
					<HelperText slot="helper">Please enter valid characters</HelperText>
				</Textfield>
			</div>
		</Card>
		<Card title="Payment Info" color="#f87171" num={4}>
			<div class="w-full bg-red-1 py-30px px-20px font-bold flex gap-2em">
				<span>
					Amount: <span class="color-red-7">$ {amount ? amount.toFixed(2) : '---'}</span>
				</span>
				<span>Shipping Fee: to be confirm</span>
			</div>
		</Card>

		<Button class="w-full h-60px" variant="raised" on:click={submit}>confirm order</Button>
	</div>
</div>

<style>
	.button-box:hover {
		filter: contrast(0.8);
	}
	.button-box:active {
		filter: brightness(0.8);
	}
	.grid-order-table {
		grid-template-columns: 1fr 1fr 4fr 1fr 1fr 1fr;
	}
</style>
